﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SunDemo.AppDbContext;
using SunDemo.Entity;

namespace SunDemo.Controllers
{
    public class MyController : Controller
    {
        //依赖注入111222
        private readonly MyDbContext myDbContext;

        public MyController(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }
        //1111
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="num1">数1</param>
        /// <param name="num2">数2</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save(int num1, int num2)
        {
            var revNum1 = ReverseNumber(num1);
            var revNum2 = ReverseNumber(num2);
            var sumNum = num1 + num2;
            var revSum = revNum1 + revNum2;

            var record = new ReverseData
            {
                Num1 = num1,
                Num2 = num2,
                RevNum1 = revNum1,
                RevNum2 = revNum2,
                SumNum = sumNum,
                RevSum = revSum
            };

            myDbContext.ReverseDatas.Add(record);
            await myDbContext.SaveChangesAsync();
            return RedirectToAction("Index");
        }


        public  int ReverseNumber(int num)
        {
            // 存储反转后的数
            int reversed = 0;
            // 输入数字是否为负数
            bool isNegative = num < 0;
            num = Math.Abs(num);
            while (num > 0)
            {
                reversed = reversed * 10 + num % 10;  // 将reversed左移一位，然后加上num的最后一位
                num = num / 10; // 去掉num的最后一位
            }
            return isNegative ? -reversed : reversed;
        }
    }
}
